package com.cms.bs.j2ee.filter;

import com.cms.bs.util.IPUtil;
import com.cms.bs.util.Log4jUtil;
import com.cms.bs.util.HttpServletRequestWrapperUtil;
import org.apache.commons.io.IOUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class LogFilter implements Filter{
	
	private String excluded;
	private String skipPath = "|/wc/chk|";

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		excluded = filterConfig.getInitParameter("excluded"); 
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		request.setCharacterEncoding("utf-8");
		HttpServletRequest req = (HttpServletRequest) request;
		String reqPath = req.getServletPath();
		HttpServletRequestWrapperUtil wrappedRequest = new HttpServletRequestWrapperUtil(req);

		if(!reqPath.startsWith(excluded) && !skipPath.contains("|" + reqPath + "|")){
			String reqMethod = req.getMethod();
			String param = null;
			if("POST".equals(reqMethod) || "PUT".equals(reqMethod) || "DELETE".equals(reqMethod)){
				String body = IOUtils.toString(wrappedRequest.getReader());
				param = req.getQueryString() + " | body:" + body;
				wrappedRequest.resetInputStream();
			}else if("GET".equals(reqMethod)){
				param = req.getQueryString();
			}
			
			// 日志 记录
			Log4jUtil.info(this.getClass().getName(), req.getScheme().toUpperCase() + ":" + reqMethod + ":" + reqPath,
					"params:" + param + "; cookies:{" + req.getHeader("cookie") + "}; ip：" + IPUtil.getIpAddr(req) );
		}
		chain.doFilter(wrappedRequest, response);
	}

	@Override
	public void destroy() {
		
	}
}
